/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "Atom.h"
#include <map>
#include <vector>
#include <Gluck.h>
#include <safe_new.h>

#ifdef ANDROID_NDK
#include <android/log.h>
#endif

#include <system/MemoryLeaks.h>

namespace liba
{

AtomStatics::AtomStatics()
:	AtomNextValue( 1 )
{
	DISABLE_LEAK_DETECTION();
	MapGlob.insert( MapType::value_type("",0) );
	VectorGlob.push_back( "" );
	ENABLE_LEAK_DETECTION();
}

AtomStatics::~AtomStatics()
{}

int AtomStatics::find_value( const std::string & str )
{
	threads::Lock lock( MutexGlob );
	DISABLE_LEAK_DETECTION();

	std::pair<AtomStatics::MapType::iterator, bool> result = MapGlob.insert( MapType::value_type(str,0) );
	if( result.second ) // just inserted
	{
		result.first->second = AtomNextValue++;
		VectorGlob.push_back( str );
	}
	ENABLE_LEAK_DETECTION();
	return result.first->second;
}

const std::string & AtomStatics::get_str(int value)const
{
	threads::Lock lock( MutexGlob );

	DISABLE_LEAK_DETECTION();
	const std::string& result = VectorGlob[ value ];
	ENABLE_LEAK_DETECTION();
	return result;
}

#ifdef VLD_DETECT_LEAKS
void AtomStatics::FreeStrings()
{
	MapGlob.clear();
	VectorGlob.clear();
}
#endif

const std::string & Atom::get_str()const
{
	return statics().get_str( value );
}

Atom::Atom(const std::string & name)
	:	value( statics().find_value(name) )
#ifdef _DEBUG
	,debug_value( name )
#endif
{}


Atom::Atom(const char * begin, const char * end)
:	value( statics().find_value( std::string(begin, end) ) )
#ifdef _DEBUG
	,debug_value(begin, end)
#endif
{}

#ifdef VLD_DETECT_LEAKS
void Atom::FreeStrings()
{
	statics().FreeStrings();
}
#endif
} // namespace liba

